package com.xrui.hbase.filter;

import com.google.common.base.Objects;
import com.xrui.hbase.DataRequest;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.KeyOnlyFilter;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.JsonNodeFactory;

import java.io.IOException;

/**
 * A RowFilter that applies HBase's KeyOnly filter to the DataRequest. This strips out
 * all values from all columns and is useful if you just want to retrieve timestamps. Note that
 * attempting to decode the data (through calls like RowData.getValues()) will
 * result in an IOException.
 */

public final class StripValueRowFilter extends RowFilter {

    /**
     * All StripValueRowFilter instances are the same: generate hash-code ahead of time.
     */
    private static final int HASH_CODE =
        new HashCodeBuilder().append(StripValueRowFilter.class).toHashCode();

    /**
     * {@inheritDoc}
     */
    @Override
    public DataRequest getDataRequest() {
        return DataRequest.builder().build();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Filter toHBaseFilter() throws IOException {
        return new KeyOnlyFilter();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean equals(Object other) {
        // All StripValueRowFilters are the same.
        return other instanceof StripValueRowFilter;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int hashCode() {
        return HASH_CODE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return Objects.toStringHelper(StripValueRowFilter.class).toString();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected JsonNode toJsonNode() {
        return JsonNodeFactory.instance.nullNode();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Class<? extends RowFilterDeserializer> getDeserializerClass() {
        return StripValueRowFilterDeserializer.class;
    }

    /**
     * De-serializes {@code StripValueRowFilter}.
     */
    public static class StripValueRowFilterDeserializer implements RowFilterDeserializer {
        /**
         * {@inheritDoc}
         */
        @Override
        public RowFilter createFromJson(JsonNode root) {
            return new StripValueRowFilter();
        }
    }
}
